<?php


namespace App\Repositories;


use App\Enums\ExportEnum;
use App\Response\Response;
use App\Exceptions\BasicException;
use App\Services\Tools\ObsService;
use App\Services\Tools\ExportService;

class ExportRepository
{
    public function export($exportNo, $condition, $header, $data)
    {
        $filename = 'export_data/' . ExportEnum::NO[$exportNo]['desc_en'] . '-' . date('Ymd-His') . '-' . mt_rand(10, 99) . app('request')->admin_id . '.xls';

        $res = app('excel')->store(new ExportService($data, $header), $filename, 'local', 'Xls');
        if(!$res){
            throw new BasicException(90030);
        }

        $localFile = storage_path('app') . '/' .$filename;
        $ossFile = $filename;
        $uploadRes = ObsService::putObs($ossFile,$localFile);
        if(!$uploadRes){
            throw new BasicException(90030);
        }
        unlink($localFile);
        $downloadUrl = env('OBS_HOST') . '/'.$filename;

        app('model_admin_export_log')->add($exportNo, $condition, $downloadUrl);

        return Response::sendData([
            'download_url' => $downloadUrl,
        ]);
    }

    /**
     * 正则表达式对emoj搜索并且使用一个回调进行替换
     * @param $str
     * @return array|string|string[]|null
     */
    public function filter_emoji($str)
    {
        $str = preg_replace_callback(
            '/./u',
            function (array $match) {
                return strlen($match[0]) >= 4 ? '' : $match[0];
            },
            $str);
        return $str;
    }
}